<?php

require CAMINHO_SERVIDOR.'conexao.php';
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of processoDAO
 *
 * @author Fernando
 */
class processoDAO {

    private $con;

    function __construct() {
        self::setCon(conectar());
        mysql_query('SET CHARACTER SET utf8');
    }

    public function getCon() {
        return $this->con;
    }

    public function setCon($con) {
        $this->con = $con;
    }

    public function fecharConexao() {
        desconectar(self::getCon());
    }

    function executaQuery($query) {
        return mysql_query($query, self::getCon());
    }

    function executaQueryAll($query) {
        $posts = array();
        $result = mysql_query($query, self::getCon());

        if (mysql_num_rows($result)) {
            while ($post = mysql_fetch_assoc($result)) {
                $posts[] = $post;
            }
        }

        return $posts;
    }

    function executaQueryRow($query) {
        $result = mysql_query($query, self::getCon());
        return mysql_fetch_assoc($result);
    }

    function getCountApostasSemProcessos($limite) {
        $query = "SELECT COUNT(id_aposta) as total FROM tb_apostas WHERE id_jogo=" . $_GET["id_jogo"] . " AND status='N' LIMIT " . $limite;
        $result = self::executaQueryRow($query);
        return $result["total"];
    }

    function getPlacarJogo($id_jogo) {
        $query = "SELECT placar_time_A,placar_time_B FROM tb_jogos WHERE id_jogo=" . $id_jogo;
        $result = self::executaQueryRow($query);
        return $result;
    }

    function getApostas($id_jogo, $limite) {
        $query = "SELECT id_aposta,id_usuario,placar_time_A,placar_time_B FROM tb_apostas WHERE id_jogo=" . $id_jogo . " AND status='N' LIMIT " . $limite;
        $result = self::executaQueryAll($query);
        return $result;
    }

    function gravaPontuacao($id_aposta, $id_usuario, $pts, $ac, $acg, $acr, $id_jogo) {
        $query = "INSERT INTO tb_pontuacao (id_aposta, id_usuario, pontos,ac,acg,acr) 
                    VALUES ('" . $id_aposta . "', '" . $id_usuario . "'," . $pts . "," . $ac . "," . $acg . "," . $acr . ") ON DUPLICATE KEY UPDATE  id_usuario=" . $id_usuario . ",pontos = " . $pts . ",ac=" . $ac . ",acg=" . $acg . ",acr=" . $acr;
        $result = self::executaQuery($query);
        if ($result) {
            $query = "UPDATE tb_apostas set status='P' WHERE id_aposta=" . $id_aposta . " AND id_usuario=" . $id_usuario . " AND id_jogo=" . $id_jogo;
            $result = self::executaQuery($query);
        }
        return $result;
    }

    function finalizaProcesso($id_jogo) {
        self::executaQuery("UPDATE tb_jogos SET status='F' WHERE id_jogo=" . $id_jogo);
    }

}
